package org.eu.huzpsb.unichat.agent.impl.c4j;

import org.eu.huzpsb.unichat.agent.Transformer;
import org.eu.huzpsb.unichat.agent.impl.c4j.search.Core;
import org.eu.huzpsb.unichat.agent.impl.c4j.search.PendingResult;
import org.eu.huzpsb.unichat.conversation.Conversation;
import org.eu.huzpsb.unichat.conversation.Entry;
import org.eu.huzpsb.unichat.conversation.EntryOwner;
import org.eu.huzpsb.unichat.exceptions.TransformerException;

import java.util.List;

public class C4JTransformer implements Transformer {
    @Override
    public Conversation beforeSend(Conversation conversation) {
        TransformerException.throwIfNotAu(conversation);
        String userPrompt = conversation.entries.get(conversation.entries.size() - 1).content;
        List<PendingResult> pendingResults = Core.doSearch(userPrompt);
        if (!pendingResults.isEmpty()) {
            StringBuilder sb = new StringBuilder();
            sb.append("[UniChat]\nThe following conversation is generated by UniChat. Do not reply to this message.\n");
            Conversation newConversation = conversation.clone();
            sb.append("Here are some web-search results that may help you:\n````txt\n");
            for (PendingResult pendingResult : pendingResults) {
                sb.append(pendingResult.asPrompt());
            }
            sb.append("````\n");
            sb.append("If any of these results are irrelevant, please simply ignore them.\n");
            sb.append("Use the Markdown hyper-link format in your answer to refer to the relevant links.\n");
            Entry entry = new Entry(EntryOwner.USER, sb.toString());
            newConversation.entries.add(entry);
            return newConversation;
        }
        return conversation;
    }

    @Override
    public Entry afterReceive(Entry entry) {
        return entry;
    }
}
